package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存访客信息
    @Override
    public String saveVisitor(Visitors visitors) {
        visitors.setDate(System.currentTimeMillis());
        visitors.setId(ObjectId.get());
        mongoTemplate.save(visitors);
        return visitors.getId().toHexString();
    }

    //根据数量查访客记录
    @Override
    public List<Visitors> topVisitor(Long userId, Integer num) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(num);
        return  getVisitors(query);
    }

    //根据时间查访客记录
    @Override
    public List<Visitors> topVisitor(Long userId, Long date) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("created").gt(date));
        return getVisitors(query);
    }

    private List<Visitors> getVisitors(Query query){
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        //查询缘分值
        for (Visitors visitors : visitorsList) {
            Query queryRecommend = Query.query(Criteria.where("userId").is(visitors.getVisitorUserId())
            .and("toUserId").is(visitors.getUserId()));
            RecommendUser recommendUser = mongoTemplate.findOne(queryRecommend, RecommendUser.class);
            if (recommendUser == null){
                visitors.setScore(30d);
            }else{
                visitors.setScore(recommendUser.getScore());
            }
        }
        return visitorsList;
    }
}